import json

from flask.blueprints import Blueprint
from flask import request, render_template, Response
from urllib.parse import unquote, quote
from src.util.pathutil import EXPORT_DIR

download_api = Blueprint('api', __name__, url_prefix="/api/download")


@download_api.route("/download_file", methods=["POST"])
def download_file():
    request_body = request.args.to_dict()
    data = request.data.decode("utf-8")
    data = json.loads(data)
    file_name = data.get("file_name")
    export_name = data.get("export_name")
    # 读取文件
    file_path = EXPORT_DIR.joinpath(file_name)
    if file_path.exists():
        stream = None
        with open(file_path, 'rb') as f:
            stream = f.read()
        if stream is not None:
            file_name = quote(export_name)
            response = Response(stream, content_type='application/octet-stream')
            # response.headers['Content-Disposition'] = 'attachment;filename*=utf-8''' + file_name
            response.headers['Content-Disposition'] = 'attachment;filename*=' + file_name
            # response.headers["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(file_name)
            # response.headers['Content-disposition'] = 'attachment; filename={}.xlsx'.format(file_name.encode("utf-8").decode('Utf-8'))
            return response
    return {
        "code": 404,
        "message": "file not found"
    }
